<template>
  <div class="moment-container">
    <div class="content-wrapper">
      <!-- 左侧推荐文章 -->
      <div class="left-sidebar">
        <div class="sidebar-card">
          <div class="card-header">
            <h3>推荐文章</h3>
          </div>
          <div class="recommended-list">
            <div v-for="item in recommendedArticles" :key="item.id" class="recommended-item" @click="handleRecommendClick(item)">
              <div class="item-title">{{ item.content.length > 12 ? item.content.slice(0, 12) + '...' : item.content }}</div>
              <div class="item-meta">
                <a-tag 
                  class="author-tag" 
                  @click.stop="goToUserProfile(item.userId)"
                >
                  {{ item.username }}
                </a-tag>
                <span>
                  <a-icon type="eye" /> 
                  {{ item.viewCount }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间内容区 -->
      <div class="main-content" ref="mainContent">
        <div class="content-header">
          <div class="header-left">
            <div class="search-wrapper">
              <a-auto-complete
                v-model="searchText"
                :dataSource="searchResults"
                @search="handleSearch"
                @select="handleSelect"
                :dropdownMatchSelectWidth="false"
                class="custom-search"
              >
                <a-input
                  slot="default"
                  placeholder="搜索仅查看最新10条记录"
                >
                  <template slot="prefix">
                    <a-icon type="search" style="color: #bfbfbf; font-size: 16px;" />
                  </template>
                </a-input>
                <template slot="dataSource">
                  <a-select-option v-for="item in searchResults" :key="item.id" :value="item.id">
                    <div class="search-option">
                      <a-avatar :size="28" :src="item.avatar">
                        {{ !item.avatar ? item.username.charAt(0).toUpperCase() : '' }}
                      </a-avatar>
                      <div class="option-content">
                        <div class="option-text">{{ item.content.length > 20 ? item.content.slice(0, 20) + '...' : item.content }}</div>
                        <div class="option-username">{{ item.username }}</div>
                      </div>
                    </div>
                  </a-select-option>
                </template>
              </a-auto-complete>
            </div>
          </div>
          <div class="header-right">
            <div class="custom-button" @click="$router.push('/social/publish')">
              <span class="plus-icon">+</span>
              发布动态
            </div>
          </div>
        </div>

        <!-- 动态列表 -->
        <div class="moment-list">
          <div v-for="item in moments" :key="item.id" class="moment-card">
            <div class="user-info" @click="goToUserProfile(item.userId)">
              <a-avatar :src="item.avatar">
                {{ !item.avatar ? item.username.charAt(0).toUpperCase() : '' }}
              </a-avatar>
              <div class="user-meta">
                <div class="username">{{ item.username }}</div>
                <div class="publish-time">{{ item.createTime }}</div>
              </div>
            </div>
            <div class="card-content" @click="goToDetail(item.id)">
              <div class="content-preview" v-html="renderContent(item.content)"></div>
              <div class="image-preview" v-if="item.imageUrl">
                <img :src="item.imageUrl" @click.stop="previewImage = item.imageUrl" />
              </div>
            </div>
            <div class="card-footer">
              <div class="interaction-stats">
                <span class="stat-item">
                  <a-icon type="eye" />
                  {{ item.viewCount }} 浏览
                </span>
                <span class="stat-item" @click.stop="goToDetail(item.id, 'comment')">
                  <a-icon type="message" />
                  {{ item.commentCount }} 评论
                </span>
                <span class="stat-item" @click.stop="handleLike(item)">
                  <a-icon :type="item.liked ? 'heart' : 'heart-o'" 
                         :class="{ 'liked': item.liked }"
                         :spin="likingMap[item.id]" />
                  {{ item.likedCount }} 点赞
                </span>
                <SharePopover
                  class="stat-item"
                  :title="item.content.slice(0, 50) + '...'"
                  :link="getShareLink(item.id)"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div class="loading-container" v-if="loading">
          <a-spin />
          <span class="loading-text">加载中...</span>
        </div>
        <div class="no-more" v-else-if="moments.length > 0 && !hasMore">
          <span>没有更多了</span>
        </div>
      </div>

      <!-- 学习资源-->
      <div class="right-sidebar">
        <div class="sidebar-card">
          <div class="card-header">
            <h3>学习资源</h3>
          </div>
          <div class="resource-list">
            <div 
              v-for="resource in learningResources" 
              :key="resource.id" 
              class="resource-item"
              @click="openResource(resource.link, resource.isInternal)"
            >
              <div class="resource-icon">
                <a-icon :type="resource.icon" />
              </div>
              <div class="resource-content">
                <div class="resource-title">{{ resource.title }}</div>
                <div class="resource-desc">{{ resource.description }}</div>
              </div>
              <a-icon class="arrow-icon" type="right" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片预览 -->
    <a-modal v-model="previewVisible" :footer="null" @cancel="previewImage = ''">
      <img alt="预览图片" style="width: 100%" :src="previewImage" />
    </a-modal>

    <!-- 回到顶部 -->
    <div class="back-to-top" v-show="showBackTop" @click="scrollToTop">
      <a-icon type="up" />
    </div>
  </div>
</template>

<script>
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import request from '@/utils/request'
import SharePopover from '@/components/SharePopover.vue'

export default {
  name: 'Moment',
  components: {
    SharePopover
  },
  data() {
    return {
      moments: [],
      loading: false,
      page: 1,
      pageSize: 5,
      total: 0,
      hasMore: true,
      previewImage: '',
      previewVisible: false,
      showBackTop: false,
      recommendedArticles: [],
      // 作者榜数据
      topAuthors: [
        { id: 1, username: '技术派', avatar: '', articleCount: 128, likeCount: '12.5k' },
        { id: 2, username: '架构师', avatar: '', articleCount: 98, likeCount: '10.2k' },
        { id: 3, username: '前端大咖', avatar: '', articleCount: 89, likeCount: '9.8k' },
        { id: 4, username: 'Java专家', avatar: '', articleCount: 76, likeCount: '8.6k' },
        { id: 5, username: '算法达人', avatar: '', articleCount: 65, likeCount: '7.9k' }
      ],
      userId: localStorage.getItem('loginId') || '',
      likingMap: {}, // 记录每个动态的点赞loading状态
      scrollListener: null,
      learningResources: [
        {
          id: 1,
          type: 'doc',
          title: 'Java开发者路线图',
          description: '最新最全Java学习路线，包含基础、框架、中间件等',
          link: '1865679336078946304',
          icon: 'file-text',
          isInternal: true
        },
        {
          id: 2,
          type: 'book',
          title: '深入理解Java虚拟机',
          description: '第3版，详解JVM原理及调优实践',
          link: '1865743636436987904',
          icon: 'book',
          isInternal: true
        },
        {
          id: 3,
          type: 'tool',
          title: 'Spring Boot 实战',
          description: '快速入门Spring Boot开发案例驱动学习',
          link: '1865744657007620096',
          icon: 'tool',
          isInternal: true
        },
        {
          id: 4,
          type: 'doc',
          title: '算法与数据结构精讲',
          description: '图解算法，由浅入深掌握数据结构',
          link: '1865745254041628672',
          icon: 'book',
          isInternal: true
        },
        {
          id: 5,
          type: 'doc',
          title: '设计模式精解',
          description: '23种设计模式，案例驱动讲解',
          link: 'https://docs.example.com/design-pattern',
          icon: 'file-text'
        }
      ],
      searchText: '',
      searchTimeout: null,
      searchResults: [],
    }
  },
  async created() {
    await Promise.all([
      this.fetchMoments(),
      this.fetchRecommendArticles()
    ])
  },
  methods: {
    async fetchMoments(isLoadMore = false) {
      if (this.loading || (!isLoadMore && !this.hasMore)) return
      
      this.loading = true
      try {
        const res = await request.post('/life/moment/queryPage', {
          page: this.page,
          pageSize: this.pageSize
        })
        
        if (res.code === 200) {
          const newMoments = res.content.list || []
          this.moments = isLoadMore ? [...this.moments, ...newMoments] : newMoments
          this.total = parseInt(res.content.total) || 0
          this.hasMore = this.moments.length < this.total
        }
      } catch (error) {
        console.error('获取动态列表失败:', error)
        this.$message.error('获取动态列表失败')
      } finally {
        this.loading = false
      }
    },
    async fetchRecommendArticles() {
      try {
        const res = await request.get('/life/moment/recommend')
        if (res.code === 200) {
          this.recommendedArticles = res.content || []
        }
      } catch (error) {
        console.error('获取推荐文章失败:', error)
      }
    },
    handleScroll() {
      const mainContent = this.$refs.mainContent
      if (!mainContent) return

      const scrollTop = window.pageYOffset || document.documentElement.scrollTop
      const windowHeight = window.innerHeight
      const documentHeight = document.documentElement.scrollHeight
      
      // 显示/隐藏回到顶部按钮
      this.showBackTop = scrollTop > 300

      // 距离底部100px时加载更多
      if (documentHeight - (scrollTop + windowHeight) < 100 && !this.loading && this.hasMore) {
        this.page++
        this.fetchMoments(true)
      }
    },
    renderContent(content) {
      if (!content) return ''
      // 只显示前200个字符
      const previewContent = content.length > 200 ? content.slice(0, 200) + '...' : content
      return DOMPurify.sanitize(marked(previewContent))
    },
    goToDetail(id, anchor) {
      const route = `/social/${id}${anchor ? '?anchor=' + anchor : ''}`
      this.$router.push(route)
    },
    handleRecommendClick(article) {
      this.goToDetail(article.id)
    },
    async handleLike(item) {
      if (!this.userId) {
        this.$message.warning('请先登录')
        return
      }
      
      this.$set(this.likingMap, item.id, true)
      try {
        const res = await request.post('/life/moment/liked/add', {
          fromId: this.userId,
          toMomentId: item.id
        })
        
        if (res.code === 200) {
          item.liked = !item.liked
          item.likedCount = item.liked ? item.likedCount + 1 : item.likedCount - 1
          this.$message.success(item.liked ? '点赞成功' : '取消点赞成功')
        }
      } catch (error) {
        console.error('点赞失败:', error)
        this.$message.error('点赞失败')
      } finally {
        this.$set(this.likingMap, item.id, false)
      }
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
    getShareLink(id) {
      // 获取当前域
      const host = window.location.origin
      return `${host}/social/${id}`
    },
    goToUserProfile(userId) {
      if (!userId) return;
      // 判断是否是当前登录用户
      const currentUserId = localStorage.getItem('loginId');
      if (userId === currentUserId) {
        this.$router.push('/profile');  // 自己的主页不带id
      } else {
        this.$router.push(`/profile/${userId}`);  // 他人主页带id
      }
    },
    openResource(link, isInternal) {
      if (isInternal) {
        this.$router.push(`/social/${link}`)
      } else {
        window.open(link, '_blank')
      }
    },
    handleSearch(value) {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout)
      }
      
      if (!value) {
        this.searchResults = []
        return
      }

      this.searchTimeout = setTimeout(async () => {
        try {
          const res = await request.post('/life/moment/queryPage', {
            page: 1,
            pageSize: 10,
            content: value
          })
          
          if (res.code === 200) {
            this.searchResults = (res.content.list || []).map(item => ({
              ...item,
              value: item.id, // 用于选择时的值
              text: item.content // 用于显示的文本
            }))
          }
        } catch (error) {
          console.error('搜索失败:', error)
        }
      }, 300)
    },
    handleSelect(value, option) {
      // 跳转到选中的动态详情页
      this.$router.push(`/social/${value}`)
    },
  },
  mounted() {
    this.scrollListener = this.handleScroll.bind(this)
    window.addEventListener('scroll', this.scrollListener)
  },
  beforeDestroy() {
    if (this.scrollListener) {
      window.removeEventListener('scroll', this.scrollListener)
    }
  }
}
</script>

<style scoped>
.moment-container {
  min-height: 100vh;
  background-color: #f8fafc;
  padding: 24px 0;
}

.content-wrapper {
  max-width: 1440px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 320px minmax(0, 1fr) 360px;
  gap: 24px;
  padding: 0 32px;
}

/* 左侧边栏样式 */
.left-sidebar {
  position: sticky;
  top: 24px;
  height: fit-content;
}

.sidebar-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  transition: all 0.3s ease;
}

.card-header {
  padding: 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  border-bottom: 1px solid #f1f5f9;
}

.card-header h3 {
  font-size: 20px;
  font-weight: 600;
  color: #0f172a;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.recommended-list {
  padding: 20px;
}

.recommended-item {
  padding: 20px;
  margin-bottom: 16px;
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid #f1f5f9;
  cursor: pointer;
  transition: all 0.3s ease;
}

.recommended-item:last-child {
  margin-bottom: 0;
}

.recommended-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-color: #e2e8f0;
}

.item-title {
  font-size: 16px;
  color: #1e293b;
  line-height: 1.6;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  font-weight: 500;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-tag {
  padding: 4px 12px !important;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%) !important;
  border: none !important;
  color: white !important;
  border-radius: 6px !important;
  font-size: 13px !important;
  font-weight: 500 !important;
  transition: all 0.3s ease !important;
}

.author-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2) !important;
}

.item-meta > span {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #64748b;
  font-size: 13px;
}

/* 主内容区样式 */
.main-content {
  background: transparent;
  min-width: 0;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: #fff;
  padding: 24px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.header-left {
  flex: 1;
  margin-right: 24px;
}

.search-wrapper {
  max-width: 600px;
  width: 100%;
  position: relative;
}

.custom-search {
  width: 100%;
}

.custom-search :deep(.ant-input-affix-wrapper) {
  border-radius: 8px;
  height: 42px;
  padding: 0 16px;
  background: #fff;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
}

.custom-search :deep(.ant-input) {
  font-size: 14px;
  background: transparent;
  height: 40px;
  border: none !important;
  box-shadow: none !important;
  padding: 0;
}

.custom-search :deep(.ant-input-prefix) {
  margin-right: 8px;
  display: flex;
  align-items: center;
}

.custom-search :deep(.ant-input-affix-wrapper:hover),
.custom-search :deep(.ant-input-affix-wrapper-focused) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.custom-search :deep(.ant-select-dropdown) {
  padding: 8px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.custom-search :deep(.ant-select-item) {
  padding: 0;
  border-radius: 6px;
}

.custom-search :deep(.ant-select-item-option-active) {
  background: #f0f7ff;
}

.custom-search :deep(.ant-select-item-option-selected) {
  background: #e6f4ff;
}

.custom-button {
  height: 48px;
  padding: 0 32px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border: none;
  border-radius: 12px;
  color: white;
  font-size: 16px;
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.1);
}

.custom-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.plus-icon {
  font-size: 20px;
  transition: transform 0.3s ease;
}

.custom-button:hover .plus-icon {
  transform: rotate(90deg);
}

.moment-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.moment-card {
  background: #fff;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
  border: 1px solid #f1f5f9;
}

.moment-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border-color: #e2e8f0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.user-meta {
  flex: 1;
  min-width: 0;
}

.username {
  font-size: 18px;
  font-weight: 600;
  color: #0f172a;
  margin-bottom: 6px;
}

.publish-time {
  font-size: 14px;
  color: #64748b;
}

.card-content {
  margin-bottom: 20px;
}

.content-preview {
  font-size: 16px;
  line-height: 1.8;
  color: #334155;
  margin-bottom: 20px;
}

.image-preview {
  border-radius: 16px;
  overflow: hidden;
  margin-bottom: 20px;
}

.image-preview img {
  width: 100%;
  transition: transform 0.3s ease;
}

.image-preview:hover img {
  transform: scale(1.02);
}

.interaction-stats {
  display: flex;
  align-items: center;
  gap: 32px;
  padding-top: 20px;
  border-top: 1px solid #f1f5f9;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #64748b;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 8px 16px;
  border-radius: 8px;
}

.stat-item:hover {
  color: #1890ff;
  background: #f0f7ff;
}

.stat-item .anticon {
  font-size: 16px;
}

.stat-item .liked {
  color: #ef4444;
}

/* 右侧边栏样式 */
.right-sidebar {
  position: sticky;
  top: 24px;
  height: fit-content;
}

.resource-list {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.resource-item {
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid #f1f5f9;
  display: flex;
  align-items: center;
  gap: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.resource-item:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-color: #e2e8f0;
}

.resource-icon {
  width: 56px;
  height: 56px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.resource-icon .anticon {
  font-size: 28px;
  transition: all 0.3s ease;
}

.resource-title {
  font-size: 16px;
  font-weight: 600;
  color: #0f172a;
  margin-bottom: 6px;
}

.resource-desc {
  font-size: 14px;
  color: #64748b;
  line-height: 1.6;
}

.arrow-icon {
  color: #94a3b8;
  font-size: 14px;
  transition: transform 0.3s ease;
}

.resource-item:hover .arrow-icon {
  transform: translateX(4px);
  color: #1890ff;
}

/* 加载状态和无更多数据样式 */
.loading-container {
  text-align: center;
  padding: 24px;
  background: #fff;
  border-radius: 16px;
  margin-top: 16px;
}

.loading-text {
  margin-left: 12px;
  color: #64748b;
  font-size: 14px;
}

.no-more {
  text-align: center;
  padding: 16px;
  background: #f8fafc;
  border-radius: 12px;
  color: #64748b;
  font-size: 14px;
  margin-top: 16px;
}

/* 回到顶部按钮 */
.back-to-top {
  position: fixed;
  right: 40px;
  bottom: 40px;
  width: 48px;
  height: 48px;
  background: #fff;
  border-radius: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  z-index: 99;
  border: 1px solid #f1f5f9;
}

.back-to-top:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.back-to-top .anticon {
  font-size: 24px;
  color: #1890ff;
}

/* 响应式布局 */
@media screen and (max-width: 1600px) {
  .content-wrapper {
    max-width: 1280px;
    grid-template-columns: 300px minmax(0, 1fr) 340px;
    gap: 20px;
    padding: 0 24px;
  }
}

@media screen and (max-width: 1400px) {
  .content-wrapper {
    max-width: 1140px;
    grid-template-columns: 280px minmax(0, 1fr) 320px;
  }
}

@media screen and (max-width: 1200px) {
  .content-wrapper {
    grid-template-columns: minmax(0, 1fr) 300px;
    max-width: 960px;
  }
  
  .left-sidebar {
    display: none;
  }
}

@media screen and (max-width: 992px) {
  .content-wrapper {
    grid-template-columns: 1fr;
    max-width: 720px;
    padding: 0 20px;
  }
  
  .right-sidebar {
    display: none;
  }
  
  .content-header {
    padding: 20px;
  }
  
  .moment-card {
    padding: 20px;
  }
}

@media screen and (max-width: 640px) {
  .moment-container {
    padding: 16px 0;
  }
  
  .content-wrapper {
    padding: 0 16px;
  }
  
  .content-header {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }
  
  .header-left {
    margin-right: 0;
  }
  
  .custom-button {
    width: 100%;
    justify-content: center;
  }
  
  .moment-card {
    padding: 16px;
  }
  
  .interaction-stats {
    gap: 16px;
    flex-wrap: wrap;
  }
  
  .stat-item {
    flex: 1;
    justify-content: center;
    padding: 8px;
  }
}

/* 搜索下拉框样式 */
.search-option {
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-radius: 6px;
}

.custom-search :deep(.ant-select-dropdown) {
  padding: 6px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.custom-search :deep(.ant-select-item) {
  padding: 0;
  border-radius: 6px;
}

.custom-search :deep(.ant-select-item-option-active) {
  background: #f0f7ff;
}

.custom-search :deep(.ant-select-item-option-selected) {
  background: #e6f4ff;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
  transition: all 0.3s ease;
}

::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style> 